package com.theeviljames.coursework.sender;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;


public class SenderTask extends Thread {

	private Socket client;
	private int delay;
	private int period;
	private SenderProtocol protocol = SenderProtocol.getInstance();
	
	public SenderTask(Socket client, int delay, int period) {
		this.client = client;
		this.delay = delay;
		this.period = period;
	}
	
	@Override
	public void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			DataOutputStream out = new DataOutputStream(client.getOutputStream());
			//Initial handshake
			out.writeBytes(protocol.getMessage(101)+"\n");
			String clientMessage = in.readLine();
			while(protocol.parseMessageString(clientMessage)!=102){
				out.writeBytes(protocol.getMessage(101)+"\n");
				clientMessage = in.readLine();
			}
			out.writeBytes(protocol.getMessage(103)+"\n");
			//Now connected
			
			clientMessage = in.readLine();
			while(protocol.parseMessageString(clientMessage)!=201){
				clientMessage = in.readLine();
			}
			out.writeBytes(protocol.getMessage(202)+delay+";PERIOD="+period+";\n");
			boolean transmitting = true;
			
			clientMessage = in.readLine();
			while(protocol.parseMessageString(clientMessage)!=501){
				if(transmitting){
					int messageID = protocol.parseMessageString(clientMessage);
					switch(messageID){
						case 303:
							int retransmitNo = parseRetransmit(clientMessage);
							out.writeBytes(protocol.encodeRetransmit(retransmitNo)+"\n");
							break;
						case 401:
							out.writeBytes(protocol.getMessage(402)+"\n");
							transmitting = false;
							break;
						default:break;
					}
				}
				else{
					if(protocol.parseMessageString(clientMessage)!=201){
						out.writeBytes(protocol.getMessage(202)+delay+"PERIOD="+period+"\n");
						transmitting = true;
					}
				}
				clientMessage = in.readLine();
			}
			out.writeBytes(protocol.getMessage(502)+"\n");
			out.close();
			in.close();
			client.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
	}
	
	public int parseRetransmit(String message){
		int a = message.indexOf("#");
		return Integer.parseInt(message.substring(a+1));
	}
}
